package ext.tianma.bom.service;

import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ext.com.iba.IBAUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.number.util.PartUtil;
import ext.tianma.project.LWCUtil;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.OneOffVersionIdentifier;
import wt.vc.OneOffVersionInfo;
import wt.vc.VersionControlHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

/**
 * 零件批准清单接口
 * 
 * @author gjw
 *
 */
@Controller
@RequestMapping({ "/ECOControl" })
public class BOMPartRecognizeService {

	private static final Logger log = LogR.getLogger(BOMPartRecognizeService.class.getName());
	// cn.tianma.RawMaterial 原材料
	private static String softype_RawMaterial = "cn.tianma.RawMaterial";

	/**
	 * 查询BOM下零件批准情况 返回 需要零件承认的零件信息
	 * 
	 * @param number
	 * @param view
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmBOMSearch", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmBOMSearch(@RequestParam(value = "number", required = true) String number,
			@RequestParam(value = "view", required = false) String view, HttpServletResponse response)
			throws Exception {
		PrintWriter out = response.getWriter();
		response.setContentType("application/json; charset=UTF-8");
		// 用户名密码校验
		String result = "";
		/*
		 * result = firstValidate(); if (!isNullOrEmpty(result)) {
		 * out.print(result); return; }
		 */
		// 逻辑处理
		result = searhPart(number, view);
		out.print(result);
	}

	/**
	 * 查询BOM中批准的零件
	 * 返回格式：{status:success/failed,datalist:[{number:XX01,partRecognize
	 * :"是",whetherPartRecognize
	 * :"是"},{number:XX02,partRecognize:"是",whetherPartRecognize:"是"}]}
	 * partRecognize：是否需要零件承认，whetherPartRecognize：是否已经样品承认
	 * 
	 * @return
	 */
	public static String searhPart(String number, String view) {
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();
		List<WTPart> list = getAllLatestVersionPart(number);
		// 找指定视图的BOM
		WTPart bompart = null;
		List<WTPart> childlist = new ArrayList<WTPart>();
		log.info("===========view:" + view);
		if (!isNullOrEmpty(view)) {
			log.info("===========view not null ==========");
			try {
				bompart = getPart(number, "", view);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			// 找BOM下的零件
			try {
				if (bompart != null) {
					childlist = getchildPart(bompart, childlist);
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
			log.info("===========view  childlist 1==========" + childlist.size());
		} else {
			log.info("===========view  null ==========");
			for (WTPart part1 : list) {
				// vect = PartUtil.getSubPartListByPart(bompart, view);
				childlist = getchildPart(part1, childlist);
			}
			log.info("===========view  childlist 2 ==========" + childlist.size());
		}

		try {
			obj.put("status", "success");
			log.info("SBOM================childlist:" + childlist.size());
			// 返回零件的信息
			for (WTPart part : childlist) {
				JSONObject object = new JSONObject();
				try {
					String softtype = (String) GenericUtil.getTypeId(part);
					System.out.println("==========softtype:"+softtype);
					if (softtype.indexOf(softype_RawMaterial) != -1) {
						String partRecognize = "";
						String whetherPartRecognize = "";
						// Hashtable values = IBAUtil.getIBAValues(part);
						ext.tianma.bom.util.IBAUtil ibas = new ext.tianma.bom.util.IBAUtil(part);
						Map ibamap = ibas.getIBAValues();
						System.out.println("=====ibamap:"+ibamap.toString());
						System.out.println(
								"=====searhPart values containsKey partRecognize:" + ibamap.containsKey("partRecognize"));
						if (ibamap.containsKey("partRecognize")) {
							whetherPartRecognize = (String) LWCUtil.getValue(part, "whetherPartRecognize");
							partRecognize = (String) LWCUtil.getValue(part, "partRecognize");
							System.out.println(
									"====whetherPartRecognize:" + whetherPartRecognize + "partRecognize:" + partRecognize);
						}

						if (!isNullOrEmpty(partRecognize) && "是".equals(partRecognize)) {
							// 零件号
							object.put("number", part.getNumber());
							object.put("name", part.getName());
							// 是否需要零件承认
							object.put("partRecognize", partRecognize);
							// 是否已经样品承认
							object.put("whetherPartRecognize", whetherPartRecognize);
							// 视图 view
							object.put("view", part.getViewName());
							// 修改者 updateBy
							object.put("updateBy", CommonPDMUtil.getModifierName(part));
							array.put(object);
						}
					}
					
				} catch (Exception e) {

					// object.put("partRecognize", "");
				}
			}
			obj.put("datalist", array);

		} catch (JSONException e) {
			log.error(e.getMessage(), e);
		}
		log.info("====ext.tianma.bom.service.BOMPartRecognizeService.searhPart:" + obj.toString());
		return obj.toString();
	}

	/**
	 * 根据编号 版本 视图返回部件
	 * 
	 * @param num
	 * @param ver
	 * @param viewName
	 * @return
	 * @throws Exception
	 */
	public static WTPart getPart(String num, String ver, String viewName) throws Exception {
		if (viewName.equals(""))
			viewName = "Design";
		if (num == null || num.equals("") || num.trim().equals(""))
			return null;
		View view = ViewHelper.service.getView(viewName);
		WTPart part = null;
		QuerySpec qs = new QuerySpec(WTPart.class);
		SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, num);
		qs.appendWhere(sc);
		sc = new SearchCondition(WTPart.class, "view.key.id", SearchCondition.EQUAL,
				view.getPersistInfo().getObjectIdentifier().getId());
		qs.appendAnd();
		qs.appendWhere(sc);
		if (!ver.equals("")) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.versionida2versioninfo"),
					SearchCondition.EQUAL, new KeywordExpression("'" + ver + "'")));
		}
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
				new KeywordExpression("1")));

		qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			part = (WTPart) qr.nextElement();
			OneOffVersionInfo one = part.getOneOffVersionInfo();
			OneOffVersionIdentifier id = one.getIdentifier();
			String valueOneOff = id.getValue();
			if (valueOneOff == null)
				return part;
		}
		return part;
	}

	/**
	 * 根据部件编号获取所有最新小版本
	 * 
	 */
	public static List<WTPart> getAllLatestVersionPart(String number) {
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = getPart(part.getNumber(), v, part.getView().getName());
				if (null != p) {
					continue;
				}
				String version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
				log.info("view:" + part.getViewName() + "===version:" + version + "<br>");
				if (!list.contains(part)) {
					list.add(part);
				}
			}
		} catch (Exception e) {

		}
		return list;

	}

	/**
	 * 空或者NULL值时返回true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str.equals("NULL"));
	}

	/**
	 * 获取关系中的部件
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static List<WTPart> getchildPart(WTPart part, List<WTPart> list) {
		try {
			QueryResult qs = WTPartHelper.service.getUsesWTPartMasters(part);
			while (qs.hasMoreElements()) {
				WTPartUsageLink link = (WTPartUsageLink) qs.nextElement();
				WTPartMaster master = (WTPartMaster) link.getRoleBObject();
				// WTPart childpart =
				// PartUtil.getLatestPartByPartMaster(master);
				WTPart childpart = getPart(master.getNumber(), "", part.getViewName());
				if (!list.contains(childpart)) {
					list.add(childpart);
				}
				if (childpart != null) {
					getchildPart(childpart, list);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

}
